# Read database of games and query

require 'chess-data'

$total_games = 0
$total_selected = 0

# read in pgn files provided on command line
ARGV.each do |file|
  puts "Reading from #{file}"

  # create a database
  database = ChessData::Database.new
  database.add_games_from file

  # display info
  puts "Read #{database.size} games"

  # extract those games which at some point reach given position definition
  selected = database.search do
    exactly 1, "R", "r"
    exactly 5, "P"
    exactly 4, "p"
  end

  # report and save result
  puts "Found #{selected.size} games"
  selected.to_file "selected.pgn"

  $total_games += database.size
  $total_selected += selected.size
end

puts "Selected #{$total_selected} out of #{$total_games}"

